package com.bluexmicro.example.page.transaction

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.*
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material3.*
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.bluexmicro.example.R
import com.bluexmicro.example.page.custom.KeepScreenOnView
import com.bluexmicro.example.page.custom.OtaTaskItemView
import com.bluexmicro.example.page.custom.StepContent
import com.bluexmicro.example.route.Route

@Composable
fun TransactionPage(
    navHostController: NavHostController,
    viewModel: TransactionViewModel
) {
    val context = LocalContext.current
    val items = remember {
        viewModel.tasks
    }
    val updating = remember {
        viewModel.updating
    }
    DisposableEffect(Unit){
        onDispose {
            viewModel.endTransaction()
        }
    }
    Scaffold(
        topBar = {
            TransactionTopBar {
                if (!updating.value) {
                    navHostController.popBackStack()
                }
            }
        }
    ) {
        Column(modifier = Modifier.fillMaxSize().padding(it)) {
            PeripheralStateBar(navHostController, viewModel)
            Divider(thickness = Dp.Hairline)
            Spacer(modifier = Modifier.height(16.dp))
            Text("任务列表", modifier = Modifier.padding(16.dp))
            LazyColumn(
                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp)
            ) {
                itemsIndexed(items) { _, item ->
                    OtaTaskItemView(item, true, onStart = { model ->
                        viewModel.execute(model)
                    }) {
                        viewModel.removeFile(context, it)
                    }
                }
                item {
                    OutlinedButton(onClick = {
                        if (!updating.value) {
                            navHostController.navigate(Route.OTA_PICK_FILE_TRANSACTION.key)
                        }
                    }, enabled = !updating.value) {
                        Text("选择固件或者素材")
                    }
                }
            }
        }
    }
}

@Composable
fun TransactionTopBar(onBack: () -> Unit) {
    Row(
        modifier = Modifier.fillMaxWidth().defaultMinSize(56.dp)
            .background(color = MaterialTheme.colorScheme.primary),
        verticalAlignment = Alignment.CenterVertically
    ) {
        TextButton(onClick = onBack) {
            Icon(
                painter = painterResource(R.drawable.ic_arrow_left),
                null,
                modifier = Modifier.size(24.dp),
                tint = MaterialTheme.colorScheme.onPrimary
            )
            Text("BX OTA", color = MaterialTheme.colorScheme.onPrimary)
        }
    }
}

@Composable
fun PeripheralStateBar(
    navHostController: NavHostController,
    viewModel: TransactionViewModel
) {
    val context = LocalContext.current
    val device = remember {
        viewModel.selectedDevice
    }
    val state = remember {
        viewModel.state
    }
    val mac = device.value?.address ?: "选择设备"
    val btnContent = when (state.value) {
        TransactionStatus.IDLE -> "开启事务"
        TransactionStatus.OPENING -> "正在开启"
        TransactionStatus.RUNNING -> "结束事务"
    }
    val updating = remember {
        viewModel.updating
    }
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier.fillMaxWidth().padding(8.dp)
    ) {
        TextButton(
            onClick = {
                navHostController.navigate(Route.OTA_PICK_PERIPHERAL_TRANSACTION.key)
            },
            modifier = Modifier.defaultMinSize(),
            contentPadding = PaddingValues(8.dp),
            enabled = !updating.value
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(mac)
                Icon(
                    painter = painterResource(R.drawable.ic_arrow_right),
                    null,
                    modifier = Modifier.size(24.dp),
                    tint = MaterialTheme.colorScheme.onBackground
                )
            }
        }
        KeepScreenOnView(modifier = Modifier.weight(1f), keepOn = updating.value)
        val startEnable =
            device.value != null && state.value != TransactionStatus.OPENING && !updating.value
        OutlinedButton(onClick = {
            if (startEnable) {
                viewModel.tapTransaction(context)
            }
        }, enabled = startEnable) {
            Text(btnContent)
        }
    }
}